<?php


namespace app\api\controller;


use app\api\model\ShopPayOrder;
use app\api\model\Users;
use app\api\model\UserStore;
use app\common\controller\Api;
use think\Db;

class Abutment extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        //dump(config('leshua.agent_id'));
        $this->success('请求成功');
    }

    public function set_order(){
        $ret['retcode'] = '0';
        $ret['retmsg'] = '';

        $res['respCode'] = '000000';
        $res['respMsg'] = '请求成功';

        $params = $this->request->param();
        //判断参数是否为空
        if (empty($params['version'])){
            $ret['retcode'] = '000001';
            $ret['retmsg'] = "必填参数为空：version";
            $res['data'] = $ret;
            return json_encode($res);
        }
        //判断参数是否为空
        if (empty($params['sign'])){
            $ret['retcode'] = '000001';
            $ret['retmsg'] = "必填参数为空：sign";
            $res['data'] = $ret;
            return json_encode($res);
        }
        //判断参数是否为空
        if (empty($params['data'])){
            $ret['retcode'] = '000001';
            $ret['retmsg'] = "必填参数为空：data";
            $res['data'] = $ret;
            return json_encode($res);
        }
        $data = htmlspecialchars_decode($params['data']);
        $data = json_decode($data,true);

        $sign  = base64_encode(strtolower(md5("lepos".config('leshua.key').json_encode($data))));
        if($sign != $params['sign']){
            $ret['retcode'] = '000002';
            $ret['retmsg'] = "签名验证失败";
            $res['data'] = $ret;
            return json_encode($res);
        }
        $version = str_replace(".","_",$params['version']);
        $str = "set_order".$version;
        return $this->{$str}($data);
    }

    /**
     * 创建订单
     * @param $user
     * @param $shop_user_id
     * @param $money
     */
    private function create_order($user,$shop_user_id,$money){
        //开启事务
        Db::startTrans();
        $trans_ok = true;

        //生成总订单
        $torder['user_id']=$user['user_id'];
        $torder['order_sn']=$this->get_order_sn();
        $torder['shop_user_id']=$shop_user_id;
        $torder['order_money']=$money;
        $torder['remark']='支付总订单';
        $torder['status']=0;
        $torder['order_type']=6;
        $torder['create_time']=time();
        $torderadd= ShopPayOrder::create($torder);
        if(!$torderadd){
            $trans_ok = false;
        }
        //dump("生成总订单：".$torderadd->id);
        //转账先以消费券为主，消费券不足则调用微信支付
        if($user['ywq']>=$money){ //消费券够付
            //生成店铺订单
            $data['user_id']=$user['user_id'];
            $data['order_sn']=$this->get_order_sn();
            $data['shop_user_id']=$shop_user_id;
            $data['money']=$money;
            $data['order_money']=$money;//20250808 改为使用消费券支付 thy
            $data['money_type']=6;
            $data['remark']='支付订单';
            $data['status']=1;
            $data['order_type']=1;
            $data['create_time']=time();
            $data['total_order_id']=$torderadd->id;

            $shopadd=ShopPayOrder::create($data);
            //dump("生成易物订单：".$shopadd->id);
            if($shopadd){
                //进行支付
                $ok1 = new_finance_record_and_add_money($user['user_id'],$money,6,2,203,$shopadd->id,$data['order_sn']);
                //dump("进行支付：".$ok1);
                if(!$ok1){
                    $trans_ok=false;
                }
            }else{
                $trans_ok=false;
            }
            if($trans_ok){
                //标志总订单为已支付
                $torderok = ShopPayOrder::where("id",$torderadd->id)->update([
                    'status'=>1,
                    'pay_time'=>time(),
                    'finish_time'=>time(),
                ]);
                //dump("标志总订单为已支付：".$torderok);
                Db::commit();
                //进行分成
                $aok = new_award($shopadd->id);
                //dump("结算结果：".$aok);
                $result['status']=2;
                $result['tuser_id']=$user['user_id'];
                $result['money']=0;
                $result['coupon']=$money;
                $result['order_sn']=$data['order_sn'];
                $result['msg']="支付成功";
            }else{
                Db::rollback();
                $result['status']=-9;
                $result['msg']="支付失败";
            }
            return $result;
        }else{ //消费券不足支付
            $wxmoney = $money;
            if($user['ywq']>0.01){
                $payywq = intval($user['ywq']*100)/100;
                $wxmoney = $money-$payywq;
                //生成店铺订单
                $data['user_id']=$user['user_id'];
                $data['order_sn']=$this->get_order_sn();
                $data['shop_user_id']=$shop_user_id;
                $data['money']=$payywq;
                $data['order_money']=$payywq;
                $data['money_type']=6;
                $data['remark']='支付订单';
                $data['status']=0;
                $data['order_type']=1;
                $data['create_time']=time();
                $data['total_order_id']=$torderadd->id;

                $shopadd=ShopPayOrder::create($data);
                if(!$shopadd){
                    $trans_ok = false;
                }
            }
            //生成微信支付订单
            //生成店铺订单
            $wxdata['user_id']=$user['user_id'];
            $wxdata['order_sn']=$this->get_order_sn();
            $wxdata['shop_user_id']=$shop_user_id;
            $wxdata['money']=$wxmoney;
            $wxdata['order_money']=$wxmoney;
            $wxdata['money_type']=1;
            $wxdata['remark']='支付订单';
            $wxdata['status']=0;
            $wxdata['order_type']=1;
            $wxdata['create_time']=time();
            $wxdata['total_order_id']=$torderadd->id;

            $shopadd2 = ShopPayOrder::create($wxdata);
            if(!$shopadd2){
                $trans_ok=false;
            }
            if($trans_ok){
                Db::commit();
                $result['status']=3;
                $result['tuser_id']=$user['user_id'];
                $result['money']=$wxmoney;
                $result['coupon']=isset($payywq)?$payywq:0;
                $result['order_sn']=$wxdata['order_sn'];
                $result['msg']="跳转到微支付";
            }else{
                Db::rollback();
                $result['status']=-8;
                $result['msg']="生成订单出错";
            }
            return $result;
        }
    }
    /**
     * 获取订单 order_sn
     * @return string
     */
    public function get_order_sn()
    {
        $order_sn = null;
        // 保证不会有重复订单号存在
        while(true){
            $order_sn = "shop".date('YmdHis').rand(1000,9999); // 订单编号
            $order_sn_count = ShopPayOrder::where(array('order_sn' => $order_sn))->count();
            if($order_sn_count == 0)
                break;
        }
        return $order_sn;
    }

    public function set_order1_0($data){
        $ret['retcode'] = '0';
        $ret['retmsg'] = 'success';

        $res['respCode'] = '000000';
        $res['respMsg'] = '成功';
        $res['version'] = '1.0';

        //获取用户信息
        $user = Users::where('openid',$data['sub_openid'])->find();
        if(!$user){
            $ret['retcode'] = '000011';
            $ret['retmsg'] = "未找到用户";
            $res['data'] = $ret;
            return json_encode($res);
        }
        //获取商户信息
        $shop = UserStore::where('merchant_id',$data['merchant_id'])->find();
        if(!$user){
            $ret['retcode'] = '000051';
            $ret['retmsg'] = "商户号不正确";
            $res['data'] = $ret;
            return json_encode($res);
        }
        //创建订单
        $cok = $this->create_order($user,$shop['user_id'],$data['amount']/100);
        if($cok['status']>0){
            $ret = array(
                "retcode" => "0",
                "retmsg" => "success",
                "merchant_id" => $data['merchant_id'],
                "third_order_id" => $cok['order_sn'],
                "amount" => $data['amount'],
                "order_amount" => $cok['money'] * 100,
                "coupon" => $cok['coupon']*100,
                "royalty" => 1,
                "appid" => config('leshua.appid'),
                "sub_openid" => $data['sub_openid'],
                "notify_url" => config('site_url')."Leshua/notify",
            );
            $res['data'] = $ret;
            return json_encode($res);
        }else{
            $ret = array(
                "retcode" => "000081",
                "retmsg" => "下单失败",
            );
            $res['data'] = $ret;
            return json_encode($res);
        }
    }
}